package com.goldgov.authentication;

import com.kcloud.ms.authentication.baseaccount.service.Account;
import com.kcloud.ms.authentication.baseaccount.service.AccountCredential;
import com.kcloud.ms.authentication.baseaccount.service.AccountCredentialService;
import com.kcloud.ms.authentication.baseaccount.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 默认登录认证类，用于非oauth2登录时检查账号是否登录及相关角色
 * @author guor
 */
@Component
public class DefaultAccountUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountCredentialService accountCredentialService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        AccountCredential accountCredential = accountCredentialService.getCredentialByName(userName);
        if (accountCredential==null){
            throw new UsernameNotFoundException(userName+"不存在。");
        }
        Account account = accountService.getAccount(accountCredential.getAccountId());
        // 增加授权角色，默认为USER，可在此处扩展查询该人员的角色相关信息
        Set<GrantedAuthority> grantedAuths = new HashSet<GrantedAuthority>();
        grantedAuths.add(new SimpleGrantedAuthority("USER"));
        User user = new User(userName, account.getPassword(), !account.getAccountState().equals(Account.ACCOUNT_STATE_DISABLED), true, true, !account.getAccountState().equals(Account.ACCOUNT_STATE_LOCKING), grantedAuths);
        return user;
    }
}
